//
//  NSDictionary+Data.m
//  JK登录注册
//
//  Created by admin on 2017/8/15.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "NSDictionary+Data.h"
#import "NSString+Hash.h"

@implementation NSDictionary (Data)

-(NSMutableDictionary *)getKeyEnumerator{
    NSArray *keyArray = [self allKeys];
    NSArray *sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortString in sortArray) {
        [valueArray addObject:[self objectForKey:sortString]];
    }
    NSMutableDictionary *input_data = [NSMutableDictionary dictionary];
    for (int i = 0; i < sortArray.count; i++) {
        [input_data setObject:valueArray[i] forKey:sortArray[i]];
    }
    //    NSLog(@"%@",input_data);
    
    return input_data;
}

-(NSString *)dictionaryToJson{
    //    NSLog(@"%zd",NSJSONWritingPrettyPrinted);
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:0 error:nil];//
    
    NSString *input = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];//
    return input;
}
- (NSString *)getData
{
    NSString *usercode = [_UserM usercode];
    NSString *ip = [NNDeviceInformation getDeviceIPAdress];
    
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970];
    NSString *times = [NSString stringWithFormat:@"%.0f", a];    //转为字符型//安卓要除以1000
    //        NSLog(@"%@", times);
    
    NSString *timekey = [times hmacSHA256StringWithKey:APPSECRET];
    
    //        NSLog(@"$timekey = %@" ,timekey);
    
    NSString *userkey = [usercode hmacSHA256StringWithKey:timekey];
    
    //        NSLog(@"$userkey = %@" ,userkey);
    
    NSString *accesskey = [ip hmacSHA256StringWithKey:userkey];
    
    //        NSLog(@"$accesskey = %@" ,accesskey);
    
    //4、对input字段进行编码
    
//    NSDictionary *input_data = @{};//@{@"mobile":@"17621218581",@"action":@"2"};//15649872106
    
    NSString *input = [[self getKeyEnumerator] dictionaryToJson];
    
    //    NSLog(@"%@",input);
    //5、计算签名
    NSString *signature = [input hmacSHA256StringWithKey:accesskey];
    //    NSLog(@"signature = %@",signature);
    //6、数据封装
    NSDictionary *dict1 = @{@"appkey":APPKEY,@"times":times,@"usercode":usercode,@"ip":ip,@"signature":signature,@"input":input};
    
    NSData *dict1_data = [NSJSONSerialization dataWithJSONObject:dict1 options:0 error:nil];
    NSString *data = [[NSString alloc]initWithData:dict1_data encoding:NSUTF8StringEncoding];
    //    NSLog(@"%@",data);
    data = [data base64Encode];
    //    NSLog(@"%@",data);
    
    return data;
}

@end
